<?php
/**
 * Created by PhpStorm.
 * User: dream
 * Date: 2017/8/19
 * Time: 20:32
 */

class MY_Model extends CI_Model
{
    protected $table_name = null;  //表名
    protected $primary_key = "id"; //主键名称 默认 id

    //初始化
    public function __construct($table_name)
    {
        parent::__construct();
        $this->load->database();
        $this->table_name = $table_name;
    }
    //添加数据
    public  function add($add_data)
    {
      $execute_res = $this->db->insert($this->table_name,$add_data);
      if($execute_res)
          return $this->db->insert_id();
      else
          return false;
    }
     //删除数据
    public  function delete($delete_where)
    {
        $delete_res = $this->db->delete($this->table_name,$delete_where);
        if($delete_res)
        {
            return $this->db->affected_rows();
        }else
            return false;
    }
    //修改数据
    public function update($update_data,$update_where)
    {
       $update_res = $this->db->update($this->table_name,$update_data,$update_where);
       if($update_data)
       {
           return $this->db->affected_rows();
       }else
           return false;

    }
    //  select * from table
    public  function get($return_array=false)
    {
       $res_obj = $this->db->get($this->table_name);
       if($return_array)
           return $res_obj->result_array();
       else
           return $res_obj->result();
    }

    // select * from table  where id = ...根据id获取数据

    public  function getById($id,$return_array=false)
    {
       $res_obj =  $this->db->get_where($this->table_name,[$this->primary_key=>$id]);

       if($return_array)
       {
           $objs = $res_obj->result();
           return reset($objs);
       }
       else
       {
           $arrays = $res_obj->result_array();
           return reset($arrays);
       }

    }

    //返回一张表的总记录数
    public   function allTableRows()
    {
        return $this->db->count_all($this->table_name);
    }

    //get where

    public function getWhere($where,$limit="",$offset="",$ctime_desc=false)
    {
        $order_by = $ctime_desc?"ctime desc":"";

        $db_datas = $this->db->order_by($order_by)->get_where($this->table_name,$where,$offset,$limit);
        return $db_datas->result();
    }
    //获取个人查询的rows

    public function getRows($where,$pattern_and=true)
    {
         if($pattern_and)
         {
            return   $this->db->where($where)->count_all_results($this->table_name);
         }
         else
             return   $this->db->or_where($where)->count_all_results($this->table_name);
    }



}